package com.groupbuying.currency.consumer.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.groupbuying.currency.consumer.connector.CustomerFeign;
import com.groupbuying.currency.consumer.connector.PayInfoFeign;
import com.groupbuying.currency.consumer.connector.SysconfigFeign;
import com.groupbuying.currency.consumer.domain.CurrencyCustomerDO;
import com.groupbuying.currency.consumer.service.CurrencyCustomerService;
import com.groupbuying.currency.consumer.utils.HttpClientUtils;
import com.groupbuying.currency.consumer.utils.RedisUtils;
import com.groupbuying.currency.consumer.utils.WeiXinUtils;
import com.groupbuying.currency.consumer.utils.apiresult.ApiResult;
import com.groupbuying.currency.consumer.utils.apiresult.ApiResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信积分变动通知，支付宝支付积分返现通知，支付宝积分变动通知
 * @Auther davidbieber
 * @Email davidbieber@163.com
 */
@Component
public class CurrencyPayNotify {
    public static final Logger LOGGER = LoggerFactory.getLogger(CurrencyPayNotify.class);

    @Autowired
    private CurrencyCustomerService currencyCustomerService;

    @Autowired
    private WeiXinUtils weiXinUtils;

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Autowired
    private PayInfoFeign payInfoFeign;

    @Autowired
    private CustomerFeign customerFeign;

    @Autowired
    private RedisUtils redisUtils;


    @Autowired
    private SysconfigFeign sysconfigFeign;

    /**
     * 微信积分变动通知
     * @param result
     * @return
     */

    public boolean CurrencyNotify(Map<String, Object> result) {
        /**
         *  prePayNo//支付单号
         *  payCurrency//支付积分
         *  customerId"//会员ID
         *  platformBusnum//平台编号
         *  orderNum"//订单号
         *  payId"//支付ID
         */
        try {
            /* 获取支付ID */
            String payId = result.get("payId").toString();
            /* 获取会员账户ID */
            String customerId = result.get("customerId").toString();
            /* 获取消费积分 */
            BigDecimal consumptionAmount = new BigDecimal(result.get("payCurrency").toString());
            if (redisUtils.isHasKey("CurrencyNotify_"+payId)) {
                return false;
            }
            /* 当前账户余额 */
            CurrencyCustomerDO currencyCustomerDO = currencyCustomerService.get(customerId);
            /* 接2消息去重，防止重复消费，并设置失效时间 */
            redisUtils.setKey("CurrencyNotify_"+payId, "currencyChangePayId",7200);
            LOGGER.info("redis消息缓存:key:{},value:{}","CurrencyNotify"+payId,redisUtils.getValue("CurrencyNotify"+payId));
            LOGGER.info("获取payId:{},customerId:{},consumptionAmount:{},currencyCustomerDO账户积分余额:{}",payId,customerId,consumptionAmount,currencyCustomerDO.getUseCurrency());
            /* 非积分消费增加积分后，微信通知用户积分变动情况 */
            /* 1. 获取微信调用access_token */
//            String accessToken = weiXinUtils.getAccessToken();
//            LOGGER.info("获取accessToken:{}",accessToken);
            /* 2. 拼接微信小程序的发送地址 */
//            String sendCurChangeUrl =
//                    "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send"
//                            + "?access_token=" + accessToken;

            /* 3. 装配微信小程序的发送包体 */
            Map<String, String> map = payInfoFeign.getInfoForCurrencyWeChatRemind(payId);
            String orderId = map.get("orderId");
            String shopName = map.get("shopName");
            String payTime = map.get("payTime");
            String payMoney = map.get("payMoney");
            String formId = map.get("formId");
            String openId = customerFeign.getOpenidByCustomerId(customerId);
            Map<String,Object> miniParams=new HashMap<>();
            miniParams.put("indicate","youdianproductor");
            miniParams.put("openId",openId);
            miniParams.put("templateId","081kV2dQOvyo1pamufAgutV8v1wKZYDYmpVHCwc9gUw");
            miniParams.put("formId",formId);
            Map<String,Object> dataParams=new HashMap<>();
            dataParams.put("keyword1",shopName);
            dataParams.put("keyword2",orderId);
            dataParams.put("keyword3",payMoney);
            dataParams.put("keyword4","-" + consumptionAmount.setScale(2, BigDecimal.ROUND_DOWN) + "积分");
            dataParams.put("keyword5",currencyCustomerDO.getUseCurrency().setScale(2,BigDecimal.ROUND_DOWN) + "积分");
            dataParams.put("keyword6",payTime);
            miniParams.put("data", JSON.toJSON(dataParams));
            LOGGER.info("拼装消息：{}",miniParams);
            ApiResult respResult = sysconfigFeign.doWechatMiniTemplateSend(miniParams);
            if(ApiResultCode.SUCCESS.code().equals(respResult.getCode())){
                LOGGER.info("模板消息发送成功");
            }else{
                LOGGER.info("模板消息发送失败");
            }





//            LOGGER.info("获取包体信息为:orderId:{},shopName:{},payTime:{},payMoney:{},formId:{},openId:{}",orderId,shopName,payTime,payMoney,formId,openId);
//            Map<String,Object> keyword1=new HashMap<>();
//            Map<String,Object> keyword2=new HashMap<>();
//            Map<String,Object> keyword3=new HashMap<>();
//            Map<String,Object> keyword4=new HashMap<>();
//            Map<String,Object> keyword5=new HashMap<>();
//            Map<String,Object> keyword6=new HashMap<>();
//            keyword1.put("value",shopName);
//            keyword2.put("value",orderId);
//            keyword3.put("value",payMoney);
//            keyword4.put("value","-" + consumptionAmount.setScale(2, BigDecimal.ROUND_DOWN) + "积分");
//            keyword5.put("value",currencyCustomerDO.getUseCurrency().setScale(2,BigDecimal.ROUND_DOWN) + "积分");
//            keyword6.put("value",payTime);
//            Map<String,Object> dataParams=new HashMap<>();
//            dataParams.put("keyword1",keyword1);
//            dataParams.put("keyword2",keyword2);
//            dataParams.put("keyword3",keyword3);
//            dataParams.put("keyword4",keyword4);
//            dataParams.put("keyword5",keyword5);
//            dataParams.put("keyword6",keyword6);
//            JSONObject jsonParams=new JSONObject();
//            jsonParams.put("touser",openId);
//            jsonParams.put("template_id","081kV2dQOvyo1pamufAgutV8v1wKZYDYmpVHCwc9gUw");
//            jsonParams.put("page","pages/home/index/index");
//            jsonParams.put("form_id",formId);
//            jsonParams.put("data",dataParams);
//            /* 4. 向微信服务器发送post请求，发送积分变动信息给用户 */
//            JSONObject returnJsonObject = httpClientUtils.doPostSendJson(sendCurChangeUrl, jsonParams);
//            LOGGER.info("消息发送返回结果:{}",returnJsonObject);
//            String errmsg = returnJsonObject.getString("errmsg");
//            LOGGER.info("错误信息:{}",errmsg);
//            String errcode = returnJsonObject.getString("errcode");
//            LOGGER.info("错误码:{}",errcode);
//            if (!errcode.equals("0") || !errmsg.equals("ok")) {
//                LOGGER.error("发送积分变动消息失败!");
//            }else{
//                LOGGER.info("消息通知成功");
//            }
//            LOGGER.info("消息通知完成");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 支付宝积分返现通知
     * @param params
     * @return
     */
//    public boolean doAliPayBackCashNotify(Map<String,Object> params){
//        try {
//            //线上支付成功，支付成功总积分
//            LOGGER.info("积分增加的参数是：{}",params);
//            /* 处理tag为CURRENCY_ADD（积分增加的消息） */
//            /* 获取支付ID */
//            String payId = params.get("payId").toString();
//            /* 获取积分账户ID */
//            String customerId = params.get("customerId").toString();
//            /* 获取消费金额 */
//            BigDecimal consumptionAmount = Object2BigDecimal
//                    .getBigDecimal(params.get("consumptionAmount"));
//            /* 获取消费返积分率 */
//            BigDecimal backCurrencyRatio = Object2BigDecimal
//                    .getBigDecimal(params.get("backCurrencyRatio"));
//            /* 消息去重，防止重复消费 */
//            if (redisUtils.isHasKey(payId)) {
//                return false;
//            }
//            /* 非积分消费增加积分并返回更新后的对象 */
//            CurrencyCustomerDO currencyCustomerDO = currencyCustomerService
//                    .addCurrencyByOnlineConsumption(customerId, payId, consumptionAmount,
//                            backCurrencyRatio);
//            /* 消息去重，防止重复消费 */
//            redisUtils.setKey(payId, "currencyChangePayId");
//            LOGGER.info("redis消息缓存key-value:{}{}",payId,redisUtils.getValue(payId));
//            LOGGER.info("获取payId:{},customerId:{},consumptionAmount:{},返积分率:{},currencyCustomerDO账户积分余额:{}",payId,customerId,consumptionAmount,backCurrencyRatio,currencyCustomerDO.getUseCurrency());
//            /* 非积分消费增加积分后，支付宝通知用户积分变动情况 */
//            /* 1. 获取支付宝alipayUserId */
//            String alipayUserId=customerFeign.getAliUserIdByCustomerId(customerId);
//            /* 3. 装配支付宝小程序的发送包体 */
//            Map<String, String> map = payInfoFeign.getInfoForCurrencyWeChatRemind(payId);
//            String orderId = map.get("orderId");
//            String shopName = map.get("shopName");
//            String payTime = map.get("payTime");
//            String payMoney = map.get("payMoney");
//            String formId = map.get("formId");
//            LOGGER.info("获取包体信息为:{}{}{}{}{}{}",orderId,shopName,payTime,payMoney,formId,alipayUserId);
//            Map<String,Object> keyword1=new HashMap<>();
//            Map<String,Object> keyword2=new HashMap<>();
//            Map<String,Object> keyword3=new HashMap<>();
//            Map<String,Object> keyword4=new HashMap<>();
//            Map<String,Object> keyword5=new HashMap<>();
//            Map<String,Object> keyword6=new HashMap<>();
//            Map<String,Object> dataParams=new HashMap<>();
//            keyword1.put("value",shopName);
//            keyword2.put("value",orderId);
//            keyword3.put("value",payMoney);
//            keyword4.put("value","+" + consumptionAmount.multiply(backCurrencyRatio).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN) + "积分");
//            keyword5.put("value",currencyCustomerDO.getUseCurrency().setScale(2,BigDecimal.ROUND_DOWN) + "积分");
//            keyword6.put("value",payTime);
//            dataParams.put("keywords1",keyword1);
//            dataParams.put("keywords2",keyword2);
//            dataParams.put("keywords3",keyword3);
//            dataParams.put("keywords4",keyword4);
//            dataParams.put("keywords5",keyword5);
//            dataParams.put("keywords6",keyword6);
//            LOGGER.info("支付宝消息模版正文消息为:{}",dataParams);
//            Map<String,Object> msgParams=new HashMap<>();
//            /**
//             * template_id 支付宝模板ID暂无
//             */
//            msgParams.put("user_template_id","template_id");
//            msgParams.put("page","pages/index/index");
//            msgParams.put("data",dataParams);
//            if(null==formId){
//                //支付消息通知，tradeNo与buyerId从支付API中的异步地址获取
//                LOGGER.info("支付消息通知");
//                String tradeNo=params.get("trade_no").toString();
//                String buyerId=params.get("buyer_id").toString();
//                if(null==tradeNo||null==buyerId){
//                    LOGGER.error(null==tradeNo?"支付宝交易账号为空":"购买用户ID为空");
//                }
//                LOGGER.info("消息模版正文消息为:{}",dataParams);
//                msgParams.put("to_user_id",buyerId);
//                msgParams.put("form_id",tradeNo);
//            }else{
//                //表单消息通知
//                LOGGER.info("表单消息通知");
//                if(null==alipayUserId){
//                    LOGGER.error("支付宝用户ID为空");
//                }
//                LOGGER.info("消息模版正文消息为:{}",dataParams);
//                msgParams.put("to_user_id",alipayUserId);
//                msgParams.put("form_id",formId);
//            }
//            //发起支付宝消息通知
//            AlipayClient alipayClient = new DefaultAlipayClient(CustomerAlipayConstants.URL,CustomerAlipayConstants.APP_ID,CustomerAlipayConstants.APP_PRIVATE_KEY,CustomerAlipayConstants.FORMAT,CustomerAlipayConstants.CHARSET,CustomerAlipayConstants.ALIPAY_PUBLIC_KEY,CustomerAlipayConstants.SIGN_TYPE);
//            AlipayOpenAppMiniTemplatemessageSendRequest request =new AlipayOpenAppMiniTemplatemessageSendRequest();
//            request.setBizContent(msgParams.toString());
//            AlipayOpenAppMiniTemplatemessageSendResponse response = alipayClient.execute(request);
//            if(response.isSuccess()){
//                System.out.println("调用成功");
//            }else{
//                System.out.println("调用失败");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return true;
//    }

    /**
     * 支付宝积分变动通知
     * @param params
     * @return
     */

    /**
     * shopName--商户名称
     * orderId--订单ID
     * payMoney--支付金额
     * 积分变动数--积分变动额
     * 积分余额--积分余额
     * payTime--支付时间
     * template_id--模版ID
     * page--小程序页面路径
     * form_id--表单ID || trade_no--支付宝交易编号
     * user_id--用户ID || buyer_id--用户ID
     */

    /**
     *shopName,formId,orderId,payTime,payMoney
     */


//    public boolean doAliPayCurrencyChangeNotify(Map<String,Object> params){
//        /* 处理tag为CURRENCY_ADD（积分增加的消息） */
//        /* 获取支付ID */
//        String payId = params.get("payId").toString();
//        /* 获取会员账户ID */
//        String customerId = params.get("customerId").toString();
//        /* 获取消费积分 */
//        BigDecimal consumptionAmount = new BigDecimal(params.get("payCurrency").toString());
//        if (redisUtils.isHasKey("CurrencyAlipayNotify"+payId)) {
//            return false;
//        }
//        /* 当前账户余额 */
//        CurrencyCustomerDO currencyCustomerDO = currencyCustomerService.get(customerId);
//        /* 消息去重，防止重复消费，并设置失效时间 */
//        redisUtils.setKey("CurrencyAlipayNotify"+payId, "currencyChangePayId",7200);
//        LOGGER.info("redis支付宝消息缓存:key:{},value:{}","CurrencyAlipayNotify"+payId,redisUtils.getValue("CurrencyAlipayNotify"+payId));
//        LOGGER.info("获取payId:{},customerId:{},consumptionAmount:{},currencyCustomerDO账户积分余额:{}",payId,customerId,consumptionAmount,currencyCustomerDO.getUseCurrency());
//        Map<String,String> currencyMap = payInfoFeign.getInfoForCurrencyWeChatRemind(payId);
//        String orderId = currencyMap.get("orderId");
//        String shopName = currencyMap.get("shopName");
//        String payTime = currencyMap.get("payTime");
//        String payMoney = currencyMap.get("payMoney");
//        String formId = currencyMap.get("formId");
//        String alipayUserId=customerFeign.getAliUserIdByCustomerId(customerId);
//        LOGGER.info("获取包体信息为:orderId:{},shopName:{},payTime:{},payMoney:{},formId:{},alipayUserId:{}",orderId,shopName,payTime,payMoney,formId,alipayUserId);
//        Map<String,Object> keyword1=new HashMap<>();
//        Map<String,Object> keyword2=new HashMap<>();
//        Map<String,Object> keyword3=new HashMap<>();
//        Map<String,Object> keyword4=new HashMap<>();
//        Map<String,Object> keyword5=new HashMap<>();
//        Map<String,Object> keyword6=new HashMap<>();
//        Map<String,Object> dataParams=new HashMap<>();
//        keyword1.put("value",shopName);
//        keyword2.put("value",orderId);
//        keyword3.put("value",payMoney);
//        keyword4.put("value","-" + consumptionAmount.setScale(2, BigDecimal.ROUND_DOWN) + "积分");
//        keyword5.put("value",currencyCustomerDO.getUseCurrency().setScale(2,BigDecimal.ROUND_DOWN) + "积分");
//        keyword6.put("value",payTime);
//        dataParams.put("keywords1",keyword1);
//        dataParams.put("keywords2",keyword2);
//        dataParams.put("keywords3",keyword3);
//        dataParams.put("keywords4",keyword4);
//        dataParams.put("keywords5",keyword5);
//        dataParams.put("keywords6",keyword6);
//        LOGGER.info("支付宝消息模版正文消息为:{}",dataParams);
//        Map<String,Object> msgParams=new HashMap<>();
//        /**
//         * template_id 支付宝模板ID暂无
//         */
//        msgParams.put("user_template_id","template_id");
//        msgParams.put("page","pages/index/index");
//        msgParams.put("data",dataParams);
//        if(null==formId){
//            //支付消息通知，tradeNo与buyerId从支付API重的异步地址获取
//            LOGGER.info("支付消息通知");
//            String tradeNo=params.get("trade_no").toString();
//            String buyerId=params.get("buyer_id").toString();
//            if(null==tradeNo||null==buyerId){
//                LOGGER.error(null==tradeNo?"支付宝交易账号为空":"购买用户ID为空");
//            }
//            LOGGER.info("支付宝积分余额消息模版正文消息为:{}",dataParams);
//            msgParams.put("to_user_id",buyerId);
//            msgParams.put("form_id",tradeNo);
//        }else{
//            //表单消息通知
//            LOGGER.info("表单消息通知");
//            if(null==alipayUserId){
//                LOGGER.error("支付宝用户ID为空");
//            }
//            LOGGER.info("消息模版正文消息为:{}",dataParams);
//            msgParams.put("to_user_id",alipayUserId);
//            msgParams.put("form_id",formId);
//        }
//        //发起支付宝消息通知
//        AlipayClient alipayClient = new DefaultAlipayClient(CustomerAlipayConstants.URL,CustomerAlipayConstants.APP_ID,CustomerAlipayConstants.APP_PRIVATE_KEY,CustomerAlipayConstants.FORMAT,CustomerAlipayConstants.CHARSET,CustomerAlipayConstants.ALIPAY_PUBLIC_KEY,CustomerAlipayConstants.SIGN_TYPE);
//        AlipayOpenAppMiniTemplatemessageSendRequest request =new AlipayOpenAppMiniTemplatemessageSendRequest();
//        request.setBizContent(msgParams.toString());
//        try{
//            AlipayOpenAppMiniTemplatemessageSendResponse response = alipayClient.execute(request);
//            if(response.isSuccess()){
//                System.out.println("调用成功");
//            }else{
//                System.out.println("调用失败");
//            }
//        }catch(Exception e){
//            LOGGER.error("支付宝消息通知发送异常:{}",e);
//            e.printStackTrace();
//        }
//        return true;
//    }

}
